package com.rtwo.salarycalculation;

import android.app.Activity;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.waps.AppConnect;
import cn.waps.AppListener;


public class MainActivity extends Activity {
    private TextView title,pension,pension_company,medical,medical_company,unemployment,unemployment_company,injury,injury_company,
            fertility,fertility_company,provident_fund,provident_fund_company,personal_total,company_total,personal_tax,company_pay,
            real_income,real_income_title;
    private Button calculate;
    private EditText preSalary;
    private Spinner cityList;
    private EditText rate;
    private ArrayAdapter<String> cityAdapter;
    private URL url;
    private int cityCode;
    private String responseJson;
    private JSONObject jsonObject;
    private MyHandler setData = new MyHandler();
    private LinearLayout adLinearLayout;

    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
                try{
                    pension.setText((String)jsonObject.get("pension"));
                    pension_company.setText((String)jsonObject.get("pension_company"));
                    medical.setText((String)jsonObject.get("medical"));
                    medical_company.setText((String)jsonObject.get("medical_company"));
                    unemployment.setText((String)jsonObject.get("unemployment"));
                    unemployment_company.setText((String)jsonObject.get("unemployment_company"));
                    injury.setText((String)jsonObject.get("injury"));
                    injury_company.setText((String)jsonObject.get("injury_company"));
                    fertility.setText((String)jsonObject.get("fertility"));
                    fertility_company.setText((String)jsonObject.get("fertility_company"));
                    provident_fund.setText((String)jsonObject.get("provident_fund"));
                    provident_fund_company.setText((String)jsonObject.get("provident_fund_company"));
                    personal_total.setText((String)jsonObject.get("personal_total"));
                    company_total.setText((String)jsonObject.get("company_total"));
                    personal_tax.setText((String)jsonObject.get("personal_tax"));
                    company_pay.setText((String)jsonObject.get("compay_pay"));
                    real_income.setText(Html.fromHtml("<u>"+jsonObject.get("real_income")+"</u>"));
                }
                catch (Exception e){
                    Toast warning = Toast.makeText(MainActivity.this,"得到错误的数据,你输入的工资可能不在税收范围",Toast.LENGTH_LONG);
                    LinearLayout waringLayout = (LinearLayout)warning.getView();
                    ImageView imageView = new ImageView(getApplicationContext());
                    imageView.setImageResource(R.drawable.toast);
                    waringLayout.addView(imageView);
                    waringLayout.setOrientation(LinearLayout.HORIZONTAL);
                    warning.show();
                }
            }
        }
    }

    void setTextStyle(TextView textView){
        textView.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/cartoon.ttf"));
    }

    void initActivity(){
        adLinearLayout = (LinearLayout)findViewById(R.id.adLinearLayout);
        title = (TextView)findViewById(R.id.title);
        real_income_title = (TextView)findViewById(R.id.real_income_title);
        pension = (TextView)findViewById(R.id.pension);
        pension_company = (TextView)findViewById(R.id.pension_company);
        medical = (TextView)findViewById(R.id.medical);
        medical_company = (TextView)findViewById(R.id.medical_company);
        unemployment = (TextView)findViewById(R.id.unemployment);
        unemployment_company = (TextView)findViewById(R.id.unemployment_company);
        injury = (TextView)findViewById(R.id.injury);
        injury_company = (TextView)findViewById(R.id.injury_company);
        fertility = (TextView)findViewById(R.id.fertility);
        fertility_company = (TextView)findViewById(R.id.fertility_company);
        provident_fund = (TextView)findViewById(R.id.provident_fund);
        provident_fund_company = (TextView)findViewById(R.id.provident_fund_company);
        personal_total = (TextView)findViewById(R.id.personal_total);
        company_total = (TextView)findViewById(R.id.company_total);
        company_pay = (TextView)findViewById(R.id.company_pay);
        real_income = (TextView)findViewById(R.id.real_income);
        personal_tax = (TextView)findViewById(R.id.personal_tax);
        calculate = (Button)findViewById(R.id.calculate);
        preSalary = (EditText)findViewById(R.id.presalary);
        cityList = (Spinner)findViewById(R.id.city);
        rate = (EditText)findViewById(R.id.rate);
        cityAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_gallery_item,new String[]{"北京","天津","上海","重庆",
                "广州","青岛","西安","深圳","杭州","南京","哈尔滨","大连","沈阳","福州","厦门","成都","武汉"});
        cityList.setAdapter(cityAdapter);
        setTextStyle(title);
    }

    boolean checkNetworkState(){
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo==null?false:true;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initActivity();
        calculate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (preSalary.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "请填入税前工资", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (rate.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "请填入公积金比例", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!checkNetworkState()){
                    Toast.makeText(MainActivity.this, "请打开您的网络,不然无法进行查询", Toast.LENGTH_SHORT).show();
                }
                switch((int)cityList.getSelectedItemId()){
                    case 0:
                        cityCode = 2;
                        break;
                    case 1:
                        cityCode = 3;
                        break;
                    case 2:
                        cityCode = 10;
                        break;
                    case 3:
                        cityCode = 23;
                        break;
                    case 4:
                        cityCode = 277;
                        break;
                    case 5:
                        cityCode = 217;
                        break;
                    case 6:
                        cityCode = 381;
                        break;
                    case 7:
                        cityCode = 279;
                        break;
                    case 8:
                        cityCode = 168;
                        break;
                    case 9:
                        cityCode = 155;
                        break;
                    case 10:
                        cityCode = 124;
                        break;
                    case 11:
                        cityCode = 102;
                        break;
                    case 12:
                        cityCode = 101;
                        break;
                    case 13:
                        cityCode = 196;
                        break;
                    case 14:
                        cityCode = 197;
                        break;
                    case 15:
                        cityCode = 328;
                        break;
                    case 16:
                        cityCode = 250;
                        break;
                    default:
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        postMsg();
                    }
                }).start();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        AppConnect.getInstance(this).close();
        super.onDestroy();
    }

    void postMsg(){
        try {
            Message msg = new Message();
            String str;
            url = new URL("http://www.yinhang.com/calc/fiveInsuranceOneFundCalc");
            HttpURLConnection http = (HttpURLConnection)url.openConnection();
            http.setRequestMethod("POST");
            http.setConnectTimeout(5000);
            http.setReadTimeout(5000);
            http.setDoInput(true);
            http.setDoOutput(true);
            http.setUseCaches(false);
            OutputStreamWriter parameter = new OutputStreamWriter(http.getOutputStream());
            parameter.write("da%5Barea_id%5D=" + cityCode + "&da%5Bincome%5D=" + preSalary.getText() + "&da%5Bprovident_fund%5D=" + rate.getText() + "&da%5Bincome_tax_type%5D=1&da%5Bcalc_type%5D=calcwage");
            parameter.flush();
            InputStreamReader response = new InputStreamReader(http.getInputStream());
            BufferedReader oResponse = new BufferedReader(response);
            StringBuffer content = new StringBuffer("");
            while((str=oResponse.readLine())!=null){
                responseJson = content.append(str).toString();
            }
            jsonObject = JSONObject.parseObject(responseJson);
            if(jsonObject!=null){
                msg.what = 1;
                setData.sendMessage(msg);
            }
            else{
                Toast.makeText(MainActivity.this,"你输入的工资可能不在税收范围或者公积金数值输入错误",Toast.LENGTH_SHORT).show();
            }
            http.disconnect();
            parameter.close();
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
